package com.alibaba.citrus.cr.order.open.api.facade.service.handler;

import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crunifiedinventory.domain.allocateorder.service.AllocateOrderService;
import com.epoch.app.crunifiedinventory.dto.response.AllocateOrderCreateResponse;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderCreateRequest;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateOrderTypeEnum;
import com.epoch.app.mninventorycenter.model.dto.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 货场提货
 *
 * @author mingyang
 * @since 2024/01/05
 */
@Component
public class FreightYardPickupHandler extends AbstractAllocateOrderCreateHandler {
    private Log log = Log.getLogger(FreightYardPickupHandler.class);

    @Autowired
    private AllocateOrderService allocateOrderService;

    @Override
    public Boolean support(TransferOrderCreateRequest request) {
        return AllocateOrderTypeEnum.FREIGHT_YARD_PICKUP.getType().equals(request.getTransferOrderType());
    }

    @Override
    public TransferOrderCreateResponse handle(TransferOrderCreateRequest request, Map<String, ScItemResponse> scItemInfoMap, WarehouseQueryResponse receiveLogicWareId, WarehouseQueryResponse deliveryLogicWareId) {
        AllocateOrderCreateRequest allocateOrderCreateRequest = getAllocateOrderCreateRequest(request,scItemInfoMap, receiveLogicWareId, deliveryLogicWareId);
        allocateOrderCreateRequest.setFeatures(getFeaturesNew(receiveLogicWareId, deliveryLogicWareId,request));
        Result<AllocateOrderCreateResponse> saveResult = allocateOrderWriteService.createAllocateOrderApi(allocateOrderCreateRequest);
        if(!saveResult.isSuccess()){
            log.error("createAllocateOrder.BetweenWarehouse,result={}", JSON.toJSONString(saveResult));
            throw new FacadeException(saveResult.getErrorCode(), saveResult.getMessage());
        }
        AllocateOrderCreateResponse result = saveResult.getResult();
        return getAllocateOrderCreateResponse(result.getCode(), result.getThirdAllocateOrderId(), result.getAllocateOrderDetailList());
    }

    @Override
    public void check(TransferOrderCreateRequest request) {
        // 有需要检查子类重写
        if (StringUtils.isEmpty(request.getRelatedAllocateOrderCode())) {
            throw new FacadeException("OTS-05-001-10-16-050", "货场提货单关联单号不能为空");
        }

        for (TransferOrderDetailRequest detailRequest : request.getTransferOrderDetailList()) {
            if (StringUtils.isEmpty(detailRequest.getRelatedAllocateSubOrderNo())) {
                throw new FacadeException("OTS-05-001-10-16-050", "货场提货单明细关联单行号不能为空");
            }
        }
    }
}
